package cn.agiledata.bank.common.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.LazyInitializationException;

import cn.agiledata.bank.account.service.AccountSummary;
import cn.agiledata.bank.account.service.IAccountConst;

/*
 * 除了登录的action，其余action均做过滤
 * （用于实现用户的单点登录、后踢前的功能）
 */
public class ActionFilter implements Filter, Constant {
	private ServletContext context;

	public ActionFilter() {
		super();
	}

	public void destroy() {
	}

	public static final List FUNCTION_LIST;
	static {
		FUNCTION_LIST = new ArrayList();
		FUNCTION_LIST.add("/page/myspace/toInitAudit.do");
		FUNCTION_LIST.add("/page/myspace/operator.do");
		FUNCTION_LIST.add("/page/myspace/toAddOperator.do");
		FUNCTION_LIST.add("/page/myspace/toOperCompetenceModify.do");
		FUNCTION_LIST.add("/page/myspace/preModifyCryptoKey.do");
		FUNCTION_LIST.add("/page/myspace/toOperCompetenceList.do");
	}
	public static final List LOGIN_STEP_LIST;
	static {
		LOGIN_STEP_LIST = new ArrayList();
		LOGIN_STEP_LIST.add("/main.do");
		LOGIN_STEP_LIST.add("/logon.do");
	}
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		String requestContextPath = request.getContextPath();

		AccountSummary accountSummary = WeatherUtil
				.getLoingInfoFromSession(request);

		// 如果是已登录用户
		if (accountSummary != null) {
			// 如果该账号又在别处登录
			if (anotherOneLogin(request, accountSummary)) {
				request.getSession().invalidate();
				response.sendRedirect(requestContextPath
						+ "/page/util/be_kicked_off.jsp");
				return;
			}
			if (Constant.ACCOUNT_TYPE_CORPORATION.equals(accountSummary
					.getAccount().getAccountType())
					&& IAccountConst.USERTYPE_CORP_OPERATOR
							.equals(accountSummary.getUserType())
					&& FUNCTION_LIST.contains(request.getServletPath())) {
				response.sendRedirect(requestContextPath
						+ "/page/myspace/nopermission.do");
				return;
			}else if("/main.do".equals(request.getServletPath())){
					response.sendRedirect(requestContextPath
							+ "/page/myspace/accountInfo.do");
					return;
				
			}
		}//else if(!LOGIN_STEP_LIST.contains(request.getServletPath())){
//			response.sendRedirect(requestContextPath
//					+ "/main.do");
//			return;
//		}

		try {
			// xss跨站脚本过滤
			String param = "";
	 	    String paramValue = "";
	 		java.util.Enumeration params = req.getParameterNames();
	 		HTMLFilter htmlFilter = new HTMLFilter(false);
	 		//循环读取参数
	 	    while (params.hasMoreElements()){
	 	    	param = (String) params.nextElement(); //获取请求中的参数
	 	    	String[] values = request.getParameterValues(param);//获得每个参数对应的值
				for (int i = 0; i < values.length; i++) {
					paramValue = values[i];
					paramValue = htmlFilter.filter(paramValue);
				}
	 	    	request.setAttribute(param, paramValue);
	 	    }
			chain.doFilter(request, response);
		} catch (LazyInitializationException e) {

		}
	}

	public void init(FilterConfig cfg) throws ServletException {
		this.context = cfg.getServletContext();
	}

	/**
	 * 是否有人已经使用该账号登录
	 * 
	 * @param request
	 * @param accountSummary
	 * @return
	 */
	public boolean anotherOneLogin(HttpServletRequest request,
			AccountSummary accountSummary) {
		boolean flag = false;
		String otherPersonSessionId;
		if (Constant.ACCOUNT_TYPE_BUYER.equals(accountSummary.getAccount()
				.getAccountType())) {

			otherPersonSessionId = (String) WebUtil.getApplicationValueByKey(
					context, accountSummary.getAccount().getId(),
					APPLICATION_SESSION_ID);

		} else {
			if (IAccountConst.USERTYPE_CORP_ADMIN.equals(accountSummary
					.getUserType())) {
				otherPersonSessionId = (String) WebUtil
						.getApplicationValueByKey(context, accountSummary
								.getOperatorCode(), APPLICATION_SESSION_ID);
			} else {
				otherPersonSessionId = (String) WebUtil
						.getApplicationValueByKey(context, accountSummary
								.getOperatorCode(), APPLICATION_SESSION_ID);
			}
		}

		if (otherPersonSessionId != null) {
			if (!request.getRequestedSessionId().equals(otherPersonSessionId)) {
				flag = true;
			}
		}
		return flag;
	}
}
